import 'package:permission_handler/permission_handler.dart';

class PermissionUtils {
  static PermissionUtils? _instance;

  PermissionUtils._();

  //懒汉式单例写法
  static PermissionUtils get instance => _instance ??= PermissionUtils._();

  // 动态申请定位权限
  Future<bool> requestPermission() async {
    // 申请权限
    bool hasLocationPermission = await _requestLocationPermission();
    return hasLocationPermission;
  }

  // 申请定位权限
  // 授予定位权限返回true， 否则返回false
  Future<bool> _requestLocationPermission() async {
    //获取当前的权限
    var status = await Permission.location.status;
    if (status == PermissionStatus.granted) {
      //已经授权
      return true;
    } else {
      //未授权则发起一次申请
      status = await Permission.location.request();
      if (status == PermissionStatus.granted) {
        return true;
      } else {
        return false;
      }
    }
  }
}
